import time
import hmac
import hashlib
import urllib.parse
import base64
import requests
from configs import setting


def generate_sign():
    timestamp = str(round(time.time() * 1000))
    secret = setting.secret
    secret_enc = secret.encode('utf-8')
    str_to_sigen = f'{timestamp}\n{secret}'
    str_to_sigen_enc = str_to_sigen.encode('utf-8')
    hmac_code = hmac.new(secret_enc, str_to_sigen_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp, sign

def send_dd_msg(content, at_all=True):
    timestamp, sign = generate_sign()
    url = f'{setting.webhook}&timestamp={timestamp}&sign={sign}'
    headers = {'Content-Type': 'application/json;charset=UTF-8'}
    data = {
        'msgtype': 'text',
        'text': {'content': content},
        'at': {'isAtAll': at_all}
    }
    res = requests.post(url=url, json=data, headers=headers)
    return res.text